import React, { useEffect, useState, useMemo } from 'react';
import {
  Modal,
  Form,
  Row,
  Col,
  Select,
  Input,
  InputNumber,
  Table,
  Button,
  Space,
  notification,
} from 'antd';
import {
  sensorSetListAll, // 查询 感测项目
  getIceMakerCemsSensorlimitsByIDAndItemID, // 上下限 默认查询
  upperLowerAdd, // 上下限 添加
  upperLowerUpdate, // 上下限 更新
  upperLowerDel, // 上下限 删除
} from './setServers';
import { selectOption } from './SettingGlobal';

const uperlimitList = [
  { name: 'Limits', value: 'LT01' },
  { name: 'Emergency Limits', value: 'LT02' },
  { name: 'Control Limits', value: 'LT03' },
];

/* 上下限 编辑 添加 */
const UpperLowerUpAdd = (props: any) => {
  const [upLowFormModal] = Form.useForm();
  const { upLowerModalVist, upLowerModalData } = props;
  const { upLowupAddModal, upLowModalOnCancel } = props;

  useEffect(() => {
    // 设置 Form 表单的默认值
    if (!upLowerModalData) {
      upLowFormModal.resetFields();
    } else {
      upLowFormModal.setFieldsValue(upLowerModalData);
    }
  }, []);

  return (
    <Modal
      title={
        upLowerModalData['TYPEMODAL'] === 'ADD'
          ? '上下限设定 添加'
          : '上下限设定 编辑'
      }
      visible={upLowerModalVist}
      maskClosable={false}
      width={800}
      onOk={() => {
        upLowFormModal.validateFields().then((val: any) => {
          let params: any = {
            itemid: val['itemid'],
            limittype: val['limittype'],
            lowerlimit: val['LOWERLIMIT'],
            upperlimit: val['UPPERLIMIT'],
          };
          if (upLowerModalData['TYPEMODAL'] === 'ADD') {
            params = { ...upLowerModalData, ...params };
          } else {
            params['id'] = upLowerModalData['ID'];
            params['lid'] = upLowerModalData['LID'];
          }

          if (upLowupAddModal(params)) {
            // upLowFormModal.resetFields();
          }
        });
      }}
      onCancel={upLowModalOnCancel}
    >
      <Form
        form={upLowFormModal}
        name="upLowFormModal"
        labelCol={{ span: 5 }}
        autoComplete="off"
      >
        <Row gutter={24} align="middle">
          <Col span={12}>
            <Form.Item label="感测项目" name="itemid">
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="Limit Type" name="limittype">
              <Input disabled />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} align="middle">
          <Col span={12}>
            <Form.Item label="下限" name="LOWERLIMIT">
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="上限" name="UPPERLIMIT">
              <InputNumber style={{ width: '100%' }} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};

/* 上下限设定 */
const SensorLimitMtn = (props: any) => {
  const [upLowForm] = Form.useForm();
  const { history, match, location } = props;

  const [selectItemIdList, setSelectItemIdList] = useState([]);
  // 表格数据
  const [tabSource, setTabSource] = useState([]);
  // 编辑 添加
  const [upLowerModalVist, setUpLowerModalVist] = useState(false);
  const [upLowerModalData, setUpLowerModalData] = useState({});

  const HistoryGoBack = () => {
    history.push('/sensorSet');
  };
  // 查询
  const getTable = () => {
    upLowForm.validateFields().then((val: any) => {
      if (val['itemid'] && val['limittype']) {
        getIceMakerCemsSensorlimitsByIDAndItemID({
          id: match['params']['id'],
          itemid: val['itemid'],
          limittype: val['limittype'],
        }).then((res) => {
          // console.log('查询到的表格数据!!!', res);
          res && setTabSource(res['data']);
        });
      }
    });
  };
  /* 上下限 Modal 关闭 */
  const upLowModalOnCancel = () => {
    setUpLowerModalVist(false);
  };
  const upLowupAddModal = (val: any) => {
    let success = true;
    if (val['TYPEMODAL'] === 'ADD') {
      delete val['TYPEMODAL'];
      upperLowerAdd(val)
        .then((res) => {
          notification.success({
            message: '上下限添加结果！',
            description: res.message || '上下限添加成功！',
          });
          setUpLowerModalVist(false);
          getTable();
        })
        .catch((rej) => {
          success = false;
          notification.error({
            message: '上下限添加结果！',
            description: rej.message || '上下限添加失败！',
          });
        });
    } else {
      upperLowerUpdate(val)
        .then((res) => {
          notification.success({
            message: '上下限添加结果！',
            description: res.message || '上下限添加成功！',
          });
          setUpLowerModalVist(false);
          getTable();
        })
        .catch((rej) => {
          success = false;
          notification.success({
            message: '上下限添加结果！',
            description: rej.message || '上下限添加成功！',
          });
        });
    }
    return success;
  };
  // 上下限 设置
  const upperLowerUpAdd = useMemo(() => {
    return (
      <UpperLowerUpAdd
        upLowerModalVist={upLowerModalVist}
        upLowerModalData={upLowerModalData}
        upLowModalOnCancel={upLowModalOnCancel}
        upLowupAddModal={upLowupAddModal}
      />
    );
  }, [upLowerModalVist]);

  useEffect(() => {
    if (!location['state']['ID'] || !location['state']['DEVICETYPE']) {
      HistoryGoBack();
      return;
    }
    // 查询 感测项目 下拉框
    sensorSetListAll({ deviceType: location['state']['DEVICETYPE'] }).then(
      (res) => {
        res && setSelectItemIdList(res['data']);
      },
    );
  }, []);

  const tableThead = [
    { title: '下限', dataIndex: 'LOWERLIMIT', key: 'LOWERLIMIT' },
    { title: '上限', dataIndex: 'UPPERLIMIT', key: 'UPPERLIMIT' },
    { title: '是否启用', dataIndex: '', key: '' },
    {
      title: '处理',
      render: (record: any) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                // console.log('编辑', upLowForm.getFieldsValue(), record );
                setUpLowerModalVist(true);
                setUpLowerModalData({
                  ...upLowForm.getFieldsValue(),
                  ...record,
                });
              }}
            >
              编辑
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                upperLowerDel({ id: record['ID'], lid: record['LID'] }).then(
                  (res) => {
                    notification.success({
                      message: '上下限删除结果！',
                      description: res.message || '上下限删除成功！',
                    });
                    getTable();
                  },
                );
              }}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  return (
    <div>
      <Row gutter={24} align="middle">
        <Col span={20}>
          <h1>上下限设定</h1>
          <h2>
            {location['state']['CNAME'] +
              '   (' +
              location['state']['ID'] +
              ')'}
          </h2>
        </Col>
        <Col span={4}>
          <Button onClick={HistoryGoBack}>返回 感测器资讯设定</Button>
        </Col>
      </Row>
      <Form
        form={upLowForm}
        name="upLowForm"
        labelCol={{ span: 5 }}
        autoComplete="off"
      >
        <Row gutter={24} align="middle">
          <Col span={12}>
            <Form.Item label="感测项目" name="itemid">
              <Select onChange={getTable}>
                {selectOption(selectItemIdList, 'ITEMID', 'ITEMDESC')}
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="Limit Type" name="limittype">
              <Select onChange={getTable}>
                {selectOption(uperlimitList, 'value', 'name')}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Form.Item>
            <Button
              type="primary"
              ghost
              onClick={() => {
                setUpLowerModalVist(true);
                setUpLowerModalData({
                  TYPEMODAL: 'ADD',
                  id: location['state']['ID'],
                  ...upLowForm.getFieldsValue(),
                });
              }}
            >
              添加
            </Button>
          </Form.Item>
        </Row>
      </Form>
      {/* 表格 */}
      <Table
        rowKey={(record: any): string =>
          record['LID'] || Math.random().toString(16)
        }
        size="middle"
        columns={tableThead}
        dataSource={tabSource}
        pagination={false}
      />
      {/* Modal 框 */}
      {upLowerModalVist && upperLowerUpAdd}
    </div>
  );
};

export default SensorLimitMtn;
